import fetch from "node-fetch";
import path from 'path';
import fs from 'fs';
import lodash from 'lodash';
import moment from "moment";
let key = '2Mwi0iRfqA9tKKlhIEcMf0xQ8h';

export class Example3 extends plugin {
    constructor() {
        super({
            name: '[SB]个人信息',
            dsc: '查看您的个人信息',
            event: 'message',
            priority: 114514,
            rule: [
                { reg: /^(#|\/)?(QQ|qq|我的|个人)信息$/, fnc: 'getInfo' },
                { reg: /^(#|\/)?查(QQ|qq)?(信息)?(\s+)?(\d+)?$/, fnc: 'getotherInfo' },
            ]
        });
    }

    async getInfo(e) {
        try {
            const qqNumber = e.user_id;
            const startTime = Date.now(); // 记录开始时间
            const userInfo = {
                user_id: e.user_id,
                nickname: e.nickname,
                card: e.member.card,
                sex: e.sender.sex,
                age: e.member.age,
                area: e.sender.area,
                last_sent_time: e.sender.last_sent_time,
                title_expire_time: e.sender.title_expire_time,
                unfriendly: e.member.unfriendly,
                card_changeable: e.member.card_changeable,
                is_robot: e.sender.is_robot,
                shut_up_timestamp: e.member.shut_up_timestamp,
                role: e.sender.role,
                title: e.member.title,
                join_time: e.member.join_time
            };
    
            const groupInfo = {
                group_id: e.group_id,
                group_name: e.group_name,
                member_count: await e.group.getMemberMap(e.group_id),
                max_member_count: this.max_member_count
            };
            // 执行多个 API 请求
            const response1 = await fetch(`https://api.76.al/api/qq/query?key=${key}&qq=${qqNumber}`);
            const text1 = await response1.text(); // 获取原始文本
            let data;
            try {
                data = JSON.parse(text1); // 尝试解析JSON
            } catch (error) {
                throw new Error(`无法解析API 1的JSON响应：${text1}`); // 如果无法解析，抛出错误
            }
    
            const response3 = await fetch(`https://apis.kit9.cn/api/qq_material/api.php?qq=${qqNumber}`);
            const text3 = await response3.text();
            let data3;
            try {
                data3 = JSON.parse(text3); // 尝试解析JSON
            } catch (error) {
                throw new Error(`无法解析API 3的JSON响应：${text3}`);
            }
    
            const response2 = await fetch(`https://api.pearktrue.cn/api/qq/money.php?qq=${qqNumber}&level=${data3.data.level}`);
            const text2 = await response2.text();
            let data2;
            try {
                data2 = JSON.parse(text2);
            } catch (error) {
                throw new Error(`无法解析API 2的JSON响应：${text2}`);
            }
    
            const response4 = await fetch(`https://api.yyx.la/api/get.info.qq?qq=${qqNumber}`);
            const text4 = await response4.text();
            let data4;
            try {
                data4 = JSON.parse(text4);
            } catch (error) {
                throw new Error(`无法解析API 4的JSON响应：${text4}`);
            }
    
            // 处理时间信息
            const regTimeStr = data.data.regTime;
            const regTime = moment(regTimeStr, "YYYY-MM-DD HH:mm:ss");
            const now = moment();
            const days = now.diff(regTime, 'days');
            const years = days / 364.24;
            const zcsc = `${days}天（约${years.toFixed(2)}年）`;
    
            if (data.code === 200) {
                //const allmessage = `状态：${data.msg}\nID：${qqNumber}\nQID：${data3.data.qid}\n昵称：${data.data.nick}\n等级：${data4.data.level}\n性别：${data3.data.gender}\n区域：${userInfo.area}\n个性签名：${data3.data.sign}\n成长速度：${data4.data.growth_rate}\n下次升级天数：${data4.data.qq_level_upgrade_days}\n会员等级：${data4.data.ivip_level}\n会员到期：${data4.data.vip_expire_time}\n大会员等级：${data4.data.ibig_level}\n注册时间：${data.data.regTime}\n注册时长：${zcsc}\n活跃天数：${data4.data.itotalactiveday}（结合VIP加速）\n邮箱：${data.data.email}\nQQ估价：${data2.data.money}\n\n群内昵称：${userInfo.card}\n群内头衔：${userInfo.title}\n群内身份：${userInfo.role}\n本群群号：${groupInfo.group_id}\n本群群名：${groupInfo.group_name}\n\n查询时间：${(Date.now() - startTime)}ms`;
                const allmessage = `状态：${data.msg}\nID：${qqNumber}\nQID：${data3.data.qid}\n昵称：${data.data.nick}\n等级：${data4.data.level}\n年龄：${data4.data.age}\n性别：${data3.data.gender}\n区域：${userInfo.area}\n个性签名：${data3.data.sign}\n会员等级：${data4.data.vip_level}\n注册时间：${data.data.regTime}\n注册时长：${zcsc}\n邮箱：${data.data.email}\nQQ估价：${data2.data.money}\n\n群内昵称：${userInfo.card}\n群内头衔：${userInfo.title}\n群内身份：${userInfo.role}\n本群群号：${groupInfo.group_id}\n本群群名：${groupInfo.group_name}\n\n查询时间：${(Date.now() - startTime)}ms`;
                const encodedMessage = encodeURIComponent(allmessage);
    
                // 设置超时机制
                const timeoutPromise = new Promise((resolve) => 
                    setTimeout(() => resolve(null), 5000) // 如果超过5秒，返回null
                );
                const fetchPromise = fetch(`http://api.chiyan.xyz/API/ark.php?wb=${encodedMessage}&wx=我补药上早八`);
    
                // 使用Promise.race进行超时控制
                const response = await Promise.race([fetchPromise, timeoutPromise]);
    
                if (response) {
                    const json = await response.json();
                    const message = {
                        type: "json",
                        data: json
                    };
                    await e.reply(message);
                } else {
                    // 超时后直接发送 allmessage
                    await e.reply(allmessage);
                }
            } else {
                await e.reply('获取用户信息失败，API返回错误。', { quote: true });
            }
        } catch (error) {
            console.error('Error fetching user information:', error);
            await e.reply(`获取用户信息时发生错误：\n${error.message}`, { quote: true });
        }
    }
    
    

    async getotherInfo(e) {
        try {
            const match = e.msg.match(/^(#|\/)?查(QQ|qq)(信息)?(\s+)?(\d+)?$/);

            // 如果消息中包含@，则优先使用@的QQ号，否则使用匹配的QQ号
            const qqNumber = e.at || (match && match[5] ? match[5].trim() : null);

                    // 检查qqNumber是否为空
            if (!qqNumber) {
                 await e.reply('你都没说你要查谁，我咋查！', { quote: true });
                 return; // 终止函数执行
            }
            const startTime = Date.now(); // 记录开始时间

            const response1 = await fetch(`https://api.76.al/api/qq/query?key=${key}&qq=${qqNumber}`);
            const text1 = await response1.text(); // 获取原始文本
            let data;
            try {
                data = JSON.parse(text1); // 尝试解析JSON
            } catch (error) {
                throw new Error(`无法解析API 1的JSON响应：${text1}`); // 如果无法解析，抛出错误
            }
    
            const response3 = await fetch(`https://apis.kit9.cn/api/qq_material/api.php?qq=${qqNumber}`);
            const text3 = await response3.text();
            let data3;
            try {
                data3 = JSON.parse(text3); // 尝试解析JSON
            } catch (error) {
                throw new Error(`无法解析API 3的JSON响应：${text3}`);
            }
    
            const response2 = await fetch(`https://api.pearktrue.cn/api/qq/money.php?qq=${qqNumber}&level=${data3.data.level}`);
            const text2 = await response2.text();
            let data2;
            try {
                data2 = JSON.parse(text2);
            } catch (error) {
                throw new Error(`无法解析API 2的JSON响应：${text2}`);
            }
    
            //const response4 = await fetch(`https://apis.kit9.cn/api/qq_new_member/api.php?qq=${qqNumber}`);
            const response4 = await fetch(`https://api.yyx.la/api/get.info.qq?qq=${qqNumber}`);
            const text4 = await response4.text();
            let data4;
            try {
                data4 = JSON.parse(text4);
            } catch (error) {
                throw new Error(`无法解析API 4的JSON响应：${text4}`);
            }


            // 从API响应中获取注册时间字符串
            const regTimeStr = data.data.regTime;

            // 使用moment.js解析注册时间
            const regTime = moment(regTimeStr, "YYYY-MM-DD HH:mm:ss");

            // 获取当前时间
            const now = moment();

            // 计算注册天数和大约多少年
            const days = now.diff(regTime, 'days');
            const years = days / 364.24;

            // 构建包含注册天数和大约年数的消息
            const zcsc = `${days}天（约${years.toFixed(2)}年）`;
   
            // 检查API返回的状态码
            if (data.code === 200) {
                const allmessage = `状态：${data.msg}\nID：${qqNumber}\nQID：${data3.data.qid}\n昵称：${data.data.nick}\n等级：${data4.data.level}\n年龄：${data4.data.age}\n性别：${data3.data.gender}\n个性签名：${data3.data.sign}\n会员等级：${data4.data.vip_level}\n注册时间：${data.data.regTime}\n注册时长：${zcsc}\n邮箱：${data.data.email}\nQQ估价：${data2.data.money}\n\n查询时间：${(Date.now() - startTime)}ms`;
    
                const encodedMessage = encodeURIComponent(allmessage);
    
                // 设置超时机制
                const timeoutPromise = new Promise((resolve) => 
                    setTimeout(() => resolve(null), 5000) // 如果超过5秒，返回null
                );
                const fetchPromise = fetch(`http://api.chiyan.xyz/API/ark.php?wb=${encodedMessage}&wx=我补药上早八`);
    
                // 使用Promise.race进行超时控制
                const response = await Promise.race([fetchPromise, timeoutPromise]);
    
                if (response) {
                    const json = await response.json();
                    const message = {
                        type: "json",
                        data: json
                    };
                    await e.reply(message);
                } else {
                    // 超时后直接发送 allmessage
                    await e.reply(allmessage);
                }
            } else {
                await e.reply('获取用户信息失败，API返回错误。', { quote: true });
            }
        } catch (error) {
            console.error('Error fetching user information:', error);
            await e.reply(`获取用户信息时发生错误：\n${JSON.stringify(error, Object.getOwnPropertyNames(error))}`, { quote: true });
        }
    }
}
